<template>
    <div class="label_manage_container">
        <Grouping ref="GroupingRef" :user-all-tag-name-list="userAllTagNameList" @submit="getGroup"></Grouping>
        <div class="label_manage_main">
            <ZwSearchForm row-num="3" :option="searchOption" @search="search" @reset="reset" />
            <!-- 表格 -->
            <ZwTable
                ref="multipleTableRef"
                class="table-box"
                tab-h="initial"
                :option="tableOption"
                :row-key="getRowKey"
                :fetch-params="state.searchParams"
                :fetch-api="fetchApi()"
                :close-loading="true"
                @selection-change="handleSelectionChange">
                <template #headerOperateLeft>
                    <div class="switchPage" style="color: #606266">最后一次同步时间：{{ sync_time }}</div>
                </template>
                <template #headerOperate>
                    <el-button v-auth="'SYNC_QW_TAGS'" plain @click="Tagsync">同步企微标签</el-button>
                    <el-button v-auth="'BAT_DEL_TAGS'" plain :disabled="sectionIds.length === 0" @click="batchDel">
                        批量删除标签
                    </el-button>
                    <el-button v-auth="'BAT_CHANGE_GP'" plain :disabled="sectionIds.length === 0" @click="batchUpdate">
                        批量更换分组
                    </el-button>
                    <el-button v-auth="'ADD_TAG'" type="primary" @click="addLabel">添加标签</el-button>
                </template>
            </ZwTable>
        </div>
        <!-- 创建、编辑弹框 -->
        <EditLable
            ref="EditLableRef"
            :label-names="labelNames"
            :default-id="groupId"
            :group-id="defaultGroupId"
            :user-tag-name-list="userTagNameList"
            @submit="AddTagBtn" />
        <!-- 删除弹框 -->
        <ZWDeletdialog ref="DeletdialogRef" @submit="del" />
    </div>
</template>

<script setup lang="ts">
import Grouping from './components/Grouping.vue';
import ZwSearchForm from '@/components/zw/search-form/SearchForm';
import ZwTable from '@/components/zw/table/Table';
import ZWDeletdialog from '@/components/ZWDeletdialog.vue';
import EditLable from './components/editLable.vue';
import { deepCopy } from '@/utils/helper';
import { ref, reactive, onMounted, computed, watch } from 'vue';
import { startLoading, endLoading } from '@/utils/request';

import {
    userTagSyncTime,
    userTagPatchDel,
    userTagUpdate,
    userTagGroupList,
    userTagList,
    userTagAdd,
    userTagDel,
    userTagPatchUpdate,
    userTagSbmit,
    userTagResults
} from '@/api/employe/label';
import { getSetionId } from '@/utils/utils';

import { useStore } from '@/store';
import { ElMessage, ElLoading } from 'element-plus';
const store = useStore();
const multipleTableRef = ref(null);
const DeletdialogRef = ref(null);
const EditLableRef = ref(null);
const GroupingRef = ref(null);
const sync_time = ref('未同步');
const isEditTag = ref(false);
const userAllTagNameList = ref([]);
const userTagNameList = ref([]);
const labelNames = ref([]);
const defaultParams = {
    title: ''
};
const state = reactive({
    searchParams: deepCopy(defaultParams)
});
const search = (v?: any) => {
    multipleTableRef.value?.clearSelection();
    state.searchParams = {
        ...deepCopy(defaultParams),
        ...v,
        group_id: groupId.value
    };
};
const reset = (v?: any) => {
    multipleTableRef.value?.clearSelection();
    state.searchParams = {
        ...deepCopy(defaultParams),
        ...v,
        group_id: groupId.value
    };
};
const fetchApi = () => {
    return userTagList;
};
const getRowKey = (row: any) => {
    return row.id;
};
const searchOption = computed(() => {
    return [
        {
            label: '标签搜索',
            name: 'title',
            value: '',
            type: 'input',
            placeholder: '请输入标签组名称/标签名搜索'
        }
    ];
});
const tableOption = [
    {
        type: 'selection',
        width: 55,
        fixed: 'left',
        reserveSelection: true
    },
    {
        prop: 'name',
        label: '标签名称',
        width: 250,
        render({ row, column, index }: any) {
            return row.name ?? '--';
        }
    },
    {
        prop: 'group_id',
        label: '所属分组',
        render({ row }: any) {
            if (userTagNameList.value.length > 0) {
                const res = userTagNameList.value.filter((item: any) => item.id == row.group_id);
                return res[0]?.name;
            } else {
                return '--';
            }
        }
    },
    {
        label: '包含员工数',
        width: 200,
        render({ row, column, index }: any) {
            return row?.work_user_count ?? '--';
        }
    },
    {
        label: '添加时间',
        width: 180,
        render({ row, column, index }: any) {
            return row?.created_at ?? '--';
        }
    },
    {
        prop: 'operate',
        label: '操作',
        width: 200,
        align: 'center',
        fixed: 'right',
        isOperate: true,
        option: [
            {
                id: 0,
                name: '编辑',
                click: (row: any) => Edit(row),
                authCode: 'EDIT_TAG',
                isRender: ({ row }: any) => row.source_type == 1
            },
            {
                id: 1,
                name: '删除',
                click: (row: any) => remove(row),
                authCode: 'DEL_TAG',
                isRender: ({ row }: any) => row.source_type == 1
            }
        ]
    }
];
// 选择IDList
const sectionIds = ref([]);
// 选中的id
const selfSelectId = ref(0);
const groupId = ref(0);
const defaultGroupId = ref(0); // 默认分组ID
// 更新标签组、新增、修改标签确认
const AddTagBtn = async (data: any) => {
    const params = {
        name: data.name,
        group_id: data.groupId,
        tag_id: selfSelectId.value
    };
    if (EditLableRef.value.showTagName) {
        isEditTag.value ? await userTagUpdate(params) : await userTagAdd(params);
        ElMessage.success(`${isEditTag.value ? '修改' : '新建'}标签组成功`);
    } else {
        // 批量更新标签组
        const res: any = await userTagPatchUpdate({
            group_id: data.groupId,
            tag_ids: sectionIds.value
        });
        ElMessage.success('批量更新标签成功');
    }
    EditLableRef.value.cancelHandel();
    GroupingRef.value.selectId = data.groupId;
    isEditTag.value = false;
    groupId.value = data.groupId;
    multipleTableRef.value?.clearSelection();
    state.searchParams = { ...state.searchParams, group_id: data.groupId };
};
// 批量更新分组标签
const batchUpdate = () => {
    EditLableRef.value.appDialog.visible = true;
    EditLableRef.value.appDialog.title = '批量更换分组';
    EditLableRef.value.showTagName = false;
    EditLableRef.value.labelForm.groupId = userTagNameList.value[0].id;
};
//是否批量
const IsBatch = ref(true);
//创建标签
const addLabel = () => {
    EditLableRef.value.appDialog.visible = true;
    EditLableRef.value.showGroup = true;
    EditLableRef.value.showTagName = true;
    EditLableRef.value.appDialog.title = '新增标签';
    isEditTag.value = false;
};
// 编辑h话术弹框
const Edit = (val: any) => {
    selfSelectId.value = val.id;
    EditLableRef.value.appDialog.visible = true;
    EditLableRef.value.appDialog.title = '编辑标签';
    isEditTag.value = true;
    EditLableRef.value.labelForm.name = val.name;
    EditLableRef.value.labelForm.groupId = val.group_id;
};
// 删除
const remove = (val: any) => {
    selfSelectId.value = val.id;
    IsBatch.value = false;
    DeletdialogRef.value.appDialog.visible = true;
};
// 批量删除
const batchDel = () => {
    IsBatch.value = true;
    DeletdialogRef.value.content =
        labelNames.value.length > 3
            ? `您确定要删除：${labelNames.value.slice(0, 3).join('、')}等${labelNames.value.length}个标签吗？`
            : `您确定要删除：${labelNames.value.slice(0, 3).join('、')}标签吗？`;
    DeletdialogRef.value.appDialog.visible = true;
};
// 删除确认
const del = async () => {
    startLoading();
    try {
        //  删除
        IsBatch.value
            ? await userTagPatchDel({
                  group_id: groupId.value,
                  tag_ids: sectionIds.value
              })
            : await userTagDel({ tag_id: selfSelectId.value });
        ElMessage.success(`${IsBatch.value ? '批量' : ''}删除成功`);
        DeletdialogRef.value.appDialog.visible = false;
        multipleTableRef.value?.clearSelection();
        state.searchParams = { ...state.searchParams };
    } catch (e) {
        endLoading();
    }
};
const getGroup = (data?: any) => {
    multipleTableRef.value?.clearSelection();
    groupId.value = data?.id;
    search(state.searchParams);
    getGroupList();
};
// 获取分组列表详情
const getGroupList = () => {
    startLoading();
    try {
        userTagGroupList().then((res: any) => {
            const result = [];
            let all = [];
            if (res.length > 1) {
                res.forEach((item: any) => {
                    result.push({
                        id: item.id,
                        name: item.name
                    });
                });
            }
            if (result.length > 1) {
                all = result.slice(1);
            }
            userTagNameList.value = all;
            userAllTagNameList.value = [
                {
                    id: res[0].id,
                    name: res[0].name,
                    children: all
                }
            ];

            defaultGroupId.value = res.filter((v: any) => v.name == '默认分组')[0].id || res[0].id;
        });
    } catch (error) {
        endLoading();
    }
};
const handleSelectionChange = (val: any) => {
    labelNames.value = getSetionId('name', val);
    sectionIds.value = getSetionId('id', val);
};
let loading: any = '';
let timer: any = null;
const onConcurrent = async (job_id: number) => {
    const res = await userTagResults({ job_id });
    loading = ElLoading.service({
        lock: true,
        text: '同步中....',
        background: 'rgba(0, 0, 0, 0.7)'
    });
    switch (res.status) {
        case 1:
            if (!timer) {
                timer = setInterval(() => {
                    onConcurrent(job_id);
                }, 4000);
            }
            break;
        case 2:
            clearInterval(timer);
            timer = null;
            // eslint-disable-next-line no-case-declarations
            const resTime = await userTagSyncTime();
            sync_time.value = resTime;
            loading.close();
            search(state.searchParams);
            ElMessage.success('同步成功');
            endLoading();
            break;
        case 3:
            clearInterval(timer);
            timer = null;
            loading.close();
            ElMessage.error('同步失败');
            endLoading();
            break;
    }
};
let loading1: any = '';
const Tagsync = async () => {
    loading1 = ElLoading.service({
        lock: true,
        text: '同步中....',
        background: 'rgba(0, 0, 0, 0.7)'
    });
    const res = await userTagSbmit();
    onConcurrent(res.id);
};
onMounted(async () => {
    getGroupList();
    const res = await userTagSyncTime();
    sync_time.value = res;
});
</script>

<style lang="scss" scoped>
.label_manage_container {
    height: calc(100vh - 142px);
    display: flex;

    .label_manage_main {
        flex: 1;
        height: calc(100vh - 142px);
        padding: 24px;
        border: 1px solid #eaeaea;
        border-radius: 4px;
        box-sizing: border-box;
        background-color: #fff;
        display: flex;
        flex-direction: column;
        overflow: hidden;

        .zw-table {
            display: flex;
            flex-direction: column;
            flex: 1;
            overflow: hidden;

            :deep(.el-table) {
                flex: 1;

                .el-table__empty-block {
                    position: absolute;
                    top: 50%;
                    left: 50%;
                    transform: translate(-50%, -50%);
                }
            }
        }
    }
}
</style>
